package com.huluobo.a2107mvpimdemo.view;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huluobo.a2107mvpimdemo.R;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.util.DateUtils;

import java.util.Date;

/**
 * Created by LC on 2023/10/7.
 */
public class SendMessageView extends RelativeLayout {
    public SendMessageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_send_message_item, this);
    }

    public void bindView(EMMessage emMessage, boolean showTimestamp) {
        updateMessage(emMessage);
        updateTimestamp(emMessage, showTimestamp);
        updateProgress(emMessage);
    }

    //绑定进度条的方法
    private void updateProgress(EMMessage emMessage) {
        ImageView send_message_progress = findViewById(R.id.send_message_progress);
        switch (emMessage.status()) {
            case INPROGRESS:
                //消息发送中,展示进度条
                send_message_progress.setVisibility(View.VISIBLE);
                send_message_progress.setImageResource(R.drawable.send_message_progress);
                AnimationDrawable animationDrawable = (AnimationDrawable) send_message_progress.getDrawable();
                animationDrawable.start();
                break;
            case SUCCESS:
                //消息发送成功,隐藏进度条
                send_message_progress.setVisibility(View.GONE);
                break;
            case FAIL:
                //消息发送失败,展示进度条,并且替换红叹号
                send_message_progress.setVisibility(View.VISIBLE);
                send_message_progress.setImageResource(R.mipmap.msg_error);
                break;
        }
    }

    //绑定时间戳的方法
    private void updateTimestamp(EMMessage emMessage, boolean showTimestamp) {
        TextView send_message_timestamp = findViewById(R.id.send_message_timestamp);
        if (showTimestamp) {
            send_message_timestamp.setVisibility(View.VISIBLE);
            send_message_timestamp.setText(DateUtils.getTimestampString(new Date(emMessage.getMsgTime())));
        } else {
            send_message_timestamp.setVisibility(View.GONE);
        }
    }

    //绑定消息的方法
    private void updateMessage(EMMessage emMessage) {
        TextView send_message_tv = findViewById(R.id.send_message_tv);
        if (emMessage.getType() == EMMessage.Type.TXT) {
            send_message_tv.setText(((EMTextMessageBody) emMessage.getBody()).getMessage());
        } else {
            send_message_tv.setText("非文本消息");
        }
    }
}
